package com.atguigu.gateway.fileter;

import com.atguigu.guli.service.base.result.ResultCodeEnum;
import com.atguigu.guli.service.base.utils.JwtHelper;
import com.google.gson.Gson;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

@Component
public class GlobalAuthFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //获取端口号后边的地址
        String path = request.getURI().getPath();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        boolean auth = antPathMatcher.match("/api/**/auth/**", path);
        if (!auth){
            //放行
            return chain.filter(exchange);
        }
        String token = request.getHeaders().getFirst("token");
        //检查token
        boolean b = JwtHelper.checkToken(token);
        if (b){
            //放行
            return chain.filter(exchange);
        }
        //封装错误信息响应给页面
        Map<Object, Object> map = new HashMap<>();
        map.put("code", ResultCodeEnum.LOGIN_AUTH.getCode());
        map.put("success",ResultCodeEnum.LOGIN_AUTH.getSuccess());
        map.put("message",ResultCodeEnum.LOGIN_AUTH.getMessage());
        //转成json字符串
        String json = new Gson().toJson(map);

        DataBuffer wrap = response.bufferFactory().wrap(json.getBytes());
        //设置响应格式
        response.getHeaders().set("content-type","application/json;charset=UTF-8");
        return response.writeWith(Mono.just(wrap));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
